import Vue from 'vue'
import VueRouter from 'vue-router'

// 页面引入
import Index from '../views/Index.vue' // 系统首页
import Set from '../views/Set.vue' // 系统首页


//  过滤重复路径抛出异常
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}


// 错误页面
const error = [
  // 404页面
  {
    path: '/404',
    name: 'notfound',
    meta: { title: '404' },
    component: () => import('../views/404.vue')
  }
]

// 设置页面
const set = [
  /**
   * set/index 一级导航/二级导航
   */
  // 一级栏目
  {
    path: 'set',
    name: 'set',
    redirect: { name: 'setIndex' },
  },
  // 二级栏目
  {
    path: 'set/index',
    name: 'setIndex',
    meta: { title: '系统设置测试栏目' },
    component: Set
  }
]

const routes = [
  {
    path: '/',
    redirect: { name: 'home' }
  },
  // 框架页面
  {
    path: '/admin',
    name: 'home',
    redirect: { name: 'index' },
    component: () => import('../views/Home.vue'),
    children: [
      // 系统首页
      {
        path: 'index',
        name: 'index',
        meta: { title: '首页' },
        component: Index
      },
      // 设置-set
      ...set
    ]
  },
  // 错误页面
  ...error,
  // 重定向
  {
    path: '*',
    redirect: { name: 'notfound' }
  }
]


const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})


// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 页面SEO设置
  to.meta.title && (document.title = to.meta.title);
  to.meta.keywords && document.querySelector('meta[name="keywords"]').setAttribute('content', to.meta.keywords);
  to.meta.description && document.querySelector('meta[name="description"]').setAttribute('content', to.meta.description);

  next();
})

// 全局后置钩子
router.afterEach((to, from) => {

})

Vue.use(VueRouter)

export default router
